package edu.umn.contactviewer.webservice;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;

import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.util.Log;
import edu.umn.contactviewer.models.Contact;
import edu.umn.contactviewer.utils.JsonSerializer;

public class WebServiceClient {
    private static final String URL_BASE = "http://contacts.tinyapollo.com/";
    private static final String SCHEME = "http";
    private static final String AUTHORITY = "contacts.tinyapollo.com";
    private static final String PATH = "contacts";
    private static final String API_KEY = "angrypenguins";

    public static ArrayList<Contact> getAllContacts() {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("Android", null);
            HttpUriRequest request = new HttpGet(URL_BASE + "contacts?key=" + API_KEY);
            HttpResponse response = client.execute(request);
            String jsonFromWebService;

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            jsonFromWebService = webServiceReader.readLine();
            webServiceReader.close();

            ArrayList<Contact> result = JsonSerializer.parseContactsFromWebService(jsonFromWebService);

            client.close();
            return result;
        }
        catch (Exception ex) {
            Log.w("GetAllContactsTask", "Error getting all contacts", ex);
        }

        return null;
    }

    public static int deleteContact(String contactId) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest request = new HttpDelete(URL_BASE + "contacts/"+ contactId + "?key=" + API_KEY);
            HttpResponse response = httpclient.execute(request);
            return response.getStatusLine().getStatusCode();
        }
        catch (Exception ex) {
            Log.w("Delete Contact Task", "Error deleting contact: " + contactId, ex);
        }
        return 404;
    }

    public static Contact addContact(Contact contact) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost request = new HttpPost( new Uri.Builder()
               .scheme( SCHEME )
               .authority( AUTHORITY )
               .path( PATH )
               .appendQueryParameter( "key", API_KEY )
               .appendQueryParameter( "name", contact.getName() )
               .appendQueryParameter( "title", contact.getTitle() )
               .appendQueryParameter( "email", contact.getEmail() )
               .appendQueryParameter( "phone", contact.getPhone() )
               .appendQueryParameter( "twitterId", contact.getTwitterId() )
               .build().toString() );
            HttpResponse response = httpclient.execute(request);

            String jsonFromWebService;
            BufferedReader webServiceReader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
            jsonFromWebService = webServiceReader.readLine();
            webServiceReader.close();
            return JsonSerializer.parseContactFromWebService(jsonFromWebService);
        }
        catch (Exception ex) {
            Log.w("AddContactTask", "Error adding contact:" + contact, ex);
        }
        return null;
    }

    public static Contact updateContact(Contact contact) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String url = new Uri.Builder()
                    .scheme( SCHEME )
                    .authority( AUTHORITY )
                    .path( PATH )
                    .appendPath(contact.get_id())
                    .appendQueryParameter( "key", API_KEY )
                    .appendQueryParameter( "name", contact.getName() )
                    .appendQueryParameter( "title", contact.getTitle() )
                    .appendQueryParameter( "email", contact.getEmail() )
                    .appendQueryParameter( "phone", contact.getPhone() )
                    .appendQueryParameter( "twitterId", contact.getTwitterId() )
                    .build().toString();
            Log.i("EditContactTask", "request url = " + url);

            HttpPut request = new HttpPut(url);
            HttpResponse response = httpclient.execute(request);

            String jsonFromWebService;
            BufferedReader webServiceReader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
            jsonFromWebService = webServiceReader.readLine();
            webServiceReader.close();
            Log.i("EditContactTask", "json:\n" + jsonFromWebService);
            return JsonSerializer.parseContactFromWebService(jsonFromWebService);
        }
        catch (Exception ex) {
            Log.w("EditContactTask", "Error updating contact", ex);
        }
        return null;
    }
}